package com.jspgou.cms.manager.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jspgou.cms.dao.RoleDao;
import com.jspgou.cms.entity.Role;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.manager.RoleMng;
import com.jspgou.cms.manager.StoreMng;
import com.jspgou.common.hibernate3.Updater;
import com.jspgou.common.page.Pagination;
import com.jspgou.core.manager.WebsiteMng;

@Service
@Transactional
public class RoleMngImpl implements RoleMng {
	@Transactional(readOnly = true)
	public Pagination getPage(int pageNo, int pageSize) {
		Pagination page = dao.getPage(pageNo, pageSize);
		return page;
	}
	
	public Pagination getPage(Long websiteId,Long storeId,int pageNo, int pageSize){
		Pagination page=dao.getPage(websiteId, storeId, pageNo, pageSize);
		return page;
	}
	
	public List<Role> getList(Long websiteId,Long storeId){
		List<Role> list=dao.getList(websiteId, storeId);
		return list;
	}

	@Transactional(readOnly = true)
	public Role findById(Long id) {
		Role entity = dao.findById(id);
		return entity;
	}
	
	public Role save(Role bean,ShopMember member){
		dao.save(bean);
		bean.addToMembers(member);
		return bean;
	}

	public Role save(Role bean,Long websiteId,Long storeId,Set<String> perms) {
		if(websiteId!=null){
			bean.setWebsite(webstieMng.findById(websiteId));
		}
		if(storeId!=null){
			bean.setStore(storeMng.findById(storeId));
		}
		bean.setPerms(perms);
		bean.setNoedit(false);
		dao.save(bean);
		return bean;
	}

	public Role update(Role bean,Set<String> perms) {
		Role role = dao.findById(bean.getId());
		bean.getPerms().clear();
		bean.setPerms(perms);
		bean.setNoedit(false);
		bean.setWebsite(role.getWebsite());
		bean.setAdmins(role.getAdmins());
		bean.setMembers(role.getMembers());
		dao.update(bean);
		return bean;
	}

	public Role deleteById(Long id) {
		Role bean = dao.deleteById(id);
		return bean;
	}
	
	public Role[] deleteByIds(Long[] ids) {
		Role[] beans = new Role[ids.length];
		for (int i = 0,len = ids.length; i < len; i++) {
			beans[i] = deleteById(ids[i]);
		}
		return beans;
	}

	private RoleDao dao;
	@Autowired
	private StoreMng storeMng;
	@Autowired
	private WebsiteMng webstieMng;
	
	@Autowired
	public void setDao(RoleDao dao) {
		this.dao = dao;
	}
}